package com.example.club_mvvm.http_hilt.mall_api

import android.util.Log
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer
import org.json.JSONObject
import retrofit2.Invocation
import java.nio.charset.StandardCharsets
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Random
import java.util.concurrent.atomic.AtomicInteger


/**
 * @author yaotianxue
 * @description
 * @date 2025/1/13
 */
class HttpMallHeaderInterceptor:Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originRequest = chain.request() //原来的请求对象
        val originBuilder =  originRequest.newBuilder()
        //1.添加请求头
        originBuilder.addHeader("platform","ANDROID")
        originBuilder.addHeader("meid","ai0d75be6be8db1f85ef1768a0157815ed")
        originBuilder.addHeader("version","1.1.5")
        originBuilder.addHeader("phoneModel","google_sdk_gphone64_x86_64")
        //2.判断post请求方式
        if(originRequest.method === "POST"){
            //3.拿到原来的请求体
            val body = originRequest.body
            //4.解析MallApiService注解获得里面service
            var service:String = ""
            val tag = originRequest.tag(Invocation::class.java)
            if(tag != null){
                val annotation = tag.method().getAnnotation(MallApiService::class.java)
                if(annotation != null){
                    service  = annotation.service
                }
            }
            Log.d("HttpMallHeaderInterceptor", "service:$service ")
            //5：将第4步获得service添加到第3步得到请求体，键值对
            //RequestBody-->String-->JsonObject(put键值对)--->String--->RequestBody
            val json = bodyToString(body)
            val jsonObject = JSONObject(json)
            jsonObject.put("channel","ANDROID")
            jsonObject.put("partnerId", PARTNER_ID)
            jsonObject.put("requestNo",genRequestNo())
            jsonObject.put("service",service)
            jsonObject.put("token","")
            jsonObject.put("version","1.0")
            val newBody = stringToBody(jsonObject.toString())
            //6.请求体添加到builder
            originBuilder.post(newBody)
            //7.添加签名
            originBuilder.addHeader("x-api-sign",createSign(newBody))
            originBuilder.addHeader("x-api-signType","MD5")
            originBuilder.addHeader("x-api-accessKey","23022113430907CF0113")
        }

        val newRequest = originBuilder.build()
        return chain.proceed(newRequest)
    }

    // 生成随机请求号
    private fun genRequestNo(): String {
        return SimpleDateFormat("yyyyMMddHHmmssSSS").format(Date()) + Random().nextInt(
            HttpMallHeaderInterceptor._counter.addAndGet(
                1
            )
        )
    }
    companion object{
        val _counter: AtomicInteger = AtomicInteger(0)
        val PARTNER_ID = "23022113430907CF0113"
    }

    /**
     * 生成签名：（请求体字符串+密钥盐）--->MD5加密
     */
    private fun createSign(newBody:RequestBody):String{
        val str =  bodyToString(newBody)
        val key = "6eef7179f83aea3986f7dd9be4c5cd8a" //密钥盐
        val buffer = Buffer()
        buffer.write(str.toByteArray(StandardCharsets.UTF_8))
        buffer.write(key.toByteArray(StandardCharsets.UTF_8))
        return buffer.md5().hex()
    }
    /**
     * RequestBody--->String
     */
    fun bodyToString(requestBody: RequestBody?):String{
        val buffer = Buffer()
        requestBody?.writeTo(buffer)
        return buffer.readUtf8()
    }

    /**
     * String--->RequestBody
     */
    fun stringToBody(str: String):RequestBody{
        val mediaType = "application/json;charset=utf.8".toMediaType()
        return str.toRequestBody(mediaType)
    }
}